/*
 * 描          述:  <描述>
 * 修  改   人:  Administrator
 * 修改时间:  2019年5月27日
 * <修改描述:>
 */
package com.tx.component.generator;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JOptionPane;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;

import com.tx.component.generator.genmodel.ControllerGenModel;
import com.tx.component.generator.genmodel.DaoGenModel;
import com.tx.component.generator.genmodel.JPADBScriptGeneratorModel;
import com.tx.component.generator.genmodel.ServiceGenModel;
import com.tx.component.generator.genmodel.SqlMapGenModel;
import com.tx.component.generator.genmodel.ValidateExpressionGenerator;
import com.tx.component.generator.genmodel.ViewGenModel;
import com.tx.component.generator.genmodel.ViewTypeEnum;
import com.tx.component.generator.genmodel.impl.JPAControllerGenModelImpl;
import com.tx.component.generator.genmodel.impl.JPADaoGeneratorModel;
import com.tx.component.generator.genmodel.impl.JPAServiceGeneratorModel;
import com.tx.component.generator.genmodel.impl.JPASqlMapGeneratorModel;
import com.tx.component.generator.genmodel.impl.JPAViewGeneratorModel;
import com.tx.component.generator.util.EntityProperty;
import com.tx.core.dbdialect.DataSourceTypeEnum;
import com.tx.core.util.FreeMarkerUtils;
import com.tx.core.util.MessageUtils;

/**
 * 代码生成器<br/>
 * <功能详细描述>
 * 
 * @author  Administrator
 * @version  [版本号, 2019年5月27日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class CodeGenerator {
    
    /** 日志记录器 */
    private static Logger logger = LoggerFactory.getLogger(CodeGenerator.class);
    
    /** 加载模板类 */
    private final static Class<?> LOAD_TEMPLATE_CLASS = CodeGenerator.class;
    
    /** 编码目录 */
    public static String BASE_CODE_FOLDER = "d:/generator/code";
    
    /** 生成代码的编码 */
    public static String DEFAULT_ENCODE = "UTF-8";
    
    /** 数据源类型 */
    public static DataSourceTypeEnum DATASOURCE_TYPE = DataSourceTypeEnum.MYSQL;
    
    /** 是否需要确认当文件已存在时 */
    public static boolean NEED_CONFIRM_WHEN_EXSITS = true;
    
    /** 脚本模板文件路径 */
    public static String DBSCRIPT = "com/tx/component/generator/ftl/mysql/dbscript.ftl";
    
    public static String SQLMAP = "com/tx/component/generator/ftl/java/sqlMap.ftl";
    
    public static String DAOIMPL = "com/tx/component/generator/ftl/java/daoImpl.ftl";
    
    public static String DAO = "com/tx/component/generator/ftl/java/dao.ftl";
    
    public static String SERVICE = "com/tx/component/generator/ftl/java/service.ftl";
    
    public static String CONTROLLER = "com/tx/component/generator/ftl/java/controller.ftl";
    
    /* --- html --- */
    public static String HTML_LIST = "com/tx/component/generator/ftl/html/html_queryList.ftl";
    
    public static String HTML_TREELIST = "com/tx/component/generator/ftl/html/html_queryTreeList.ftl";
    
    public static String HTML_PAGESLIST = "com/tx/component/generator/ftl/html/html_queryPagedList.ftl";
    
    public static String HTML_ADD = "com/tx/component/generator/ftl/html/html_add.ftl";
    
    public static String HTML_UPDATE = "com/tx/component/generator/ftl/html/html_update.ftl";
    
    /* --- vue --- */
    public static String TS_API = "com/tx/component/generator/ftl/vue/ts_api.ftl";
    
    public static String VUE_LIST = "com/tx/component/generator/ftl/vue/vue_list.ftl";
    
    public static String VUE_TREELIST = "com/tx/component/generator/ftl/vue/vue_treelist.ftl";
    
    public static String VUE_PAGESLIST = "com/tx/component/generator/ftl/vue/vue_pageslist.ftl";
    
    public static String VUE_ADD = "com/tx/component/generator/ftl/vue/vue_add.ftl";
    
    public static String VUE_UPDATE = "com/tx/component/generator/ftl/vue/vue_update.ftl";
    
    /** easyui的验证表达式生成器 */
    private final static ValidateExpressionGenerator HTML_VALIDATE_EXPRESSION_GENERATOR = new ValidateExpressionGenerator() {
        @Override
        public void generate(EntityProperty property, Class<?> entityType) {
            String validateExpression = null;
            if (String.class.getName().equals(property.getPropertyTypeName())) {
                if (property.getPropertyName().endsWith("Id")
                        || property.getPropertyName().endsWith("Code")) {
                    return;
                } else if ("code".equals(property.getPropertyName())) {
                    //required:true,validType:["remote['/noticeCategory/validate','code','id']","code"],delay:400
                    validateExpression = "required:true,validType:[\"remote['/"
                            + StringUtils
                                    .uncapitalize(entityType.getSimpleName())
                            + "/validate', 'code', 'id']\",\"code\"],delay:400";
                } else if ("name".equals(property.getPropertyName())) {
                    //required:true,validType:["remote['/noticeCategory/validate','name','id']"],delay:400
                    validateExpression = "required:true,validType:[\"remote['/"
                            + entityType.getSimpleName()
                                    .replaceAll("([a-z])([A-Z]+)", "$1_$2")
                                    .toLowerCase()
                            + "/exist', 'name', 'id']\"],delay:400";
                } else if ("remark".equals(property.getPropertyName())) {
                    //multiline:true
                    validateExpression = "";
                } else if (!property.isNullable()) {
                    //required:true
                    validateExpression = "required:true";
                } else {
                    //
                    validateExpression = "";
                }
            } else {
                if (!property.isNullable()) {
                    //required:true
                    validateExpression = "required:true";
                } else {
                    //
                    validateExpression = "";
                }
            }
            property.setValidateExpression(validateExpression);
        }
    };
    
    /** easyui的验证表达式生成器 */
    private final static ValidateExpressionGenerator VUE_VALIDATE_EXPRESSION_GENERATOR = new ValidateExpressionGenerator() {
        @Override
        public void generate(EntityProperty property, Class<?> entityType) {
            String validateExpression = null;
            if (String.class.getName().equals(property.getPropertyTypeName())) {
                if (property.getPropertyName().endsWith("Id")
                        || property.getPropertyName().endsWith("Code")) {
                    return;
                } else if ("code".equals(property.getPropertyName())) {
                    /*
                    [{ message: '编码不能为空', required: true, trigger: 'blur' },
                     { message: '编码已经存在', validator: validatorRemoteWrap(exists, (value) => {
                        const params = {};
                        params['code'] = value;
                        return params;
                      }),
                      trigger: 'blur',
                      },
                    ]
                    */
                    validateExpression = "[{ message: '编码不能为空', required: true, trigger: 'blur' },\r\n"
                            + "                     { message: '编码已经存在', validator: validatorRemoteWrap(exists, (value) => {\r\n"
                            + "                        const params = {};\r\n"
                            + "                        params['code'] = value;\r\n"
                            + "                        return params;\r\n"
                            + "                      }),\r\n"
                            + "                      trigger: 'blur',\r\n"
                            + "                      },\r\n"
                            + "                    ]";
                } else if ("name".equals(property.getPropertyName())) {
                    //[{ message: '名称不能为空', required: true, trigger: 'blur' }]
                    validateExpression = "[{ message: '名称不能为空', required: true, trigger: 'blur' }]";
                } else if ("remark".equals(property.getPropertyName())) {
                    //multiline:true
                    validateExpression = "";
                } else if (!property.isNullable()) {
                    //required:true
                    validateExpression = "[{ message: '不能为空', required: true, trigger: 'blur' }]";
                } else {
                    //
                    validateExpression = "";
                }
            } else {
                if (!property.isNullable()) {
                    //required:true
                    validateExpression = "[{ message: '不能为空', required: true, trigger: 'blur' }]";
                } else {
                    //
                    validateExpression = "";
                }
            }
            property.setValidateExpression(validateExpression);
        }
    };
    
    /**
     * 生成视图逻辑<br/>
     * <功能详细描述>
     * @param entityType [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     */
    public static <T> void generateVue(Class<?> entityType) {
        generateVue(entityType,
                ViewTypeEnum.LIST,
                "/src/main/resources/templates/");
    }
    
    /**
     * 生成视图逻辑<br/>
     * <功能详细描述>
     * @param <T>
     * @param entityType
     * @param viewType [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     */
    public static <T> void generateVue(Class<?> entityType,
            ViewTypeEnum viewType) {
        generateVue(entityType, viewType, "/view/admin/src/");
    }
    
    /**
     * 生成视图逻辑<br/>
     * <功能详细描述>
     * @param entityType
     * @param viewType [参数说明]
     * @param templateFolderPath 
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     */
    public static <T> void generateVue(Class<?> entityType,
            ViewTypeEnum viewType, String templateFolderPath) {
        viewType = viewType == null ? ViewTypeEnum.LIST : viewType;
        ViewGenModel viewModel = new JPAViewGeneratorModel(entityType,
                VUE_VALIDATE_EXPRESSION_GENERATOR);
        
        Map<String, Object> data = new HashMap<String, Object>();
        String packageName = getPackageName(entityType);
        data.put("view", viewModel);
        data.put("packageName", packageName);
        
        String basePath = ClassUtils.convertClassNameToResourcePath(
                entityType.getName()) + "/../..";
        basePath = org.springframework.util.StringUtils.cleanPath(basePath);
        
        String tsFilePath = BASE_CODE_FOLDER + templateFolderPath + "/api/"
                + packageName + "/"
                + entityType.getSimpleName()
                        .replaceAll("([a-z])([A-Z]+)", "$1_$2")
                        .toLowerCase()
                + ".ts";
        if (isOverwrite(tsFilePath)) {
            logger.info("TS_API存放路径:{}", tsFilePath);
            FreeMarkerUtils
                    .fprint(LOAD_TEMPLATE_CLASS, TS_API, data, tsFilePath);
        }
        
        String addFilePath = BASE_CODE_FOLDER + templateFolderPath + "/views/"
                + packageName + "/"
                + entityType.getSimpleName()
                        .replaceAll("([a-z])([A-Z]+)", "$1_$2")
                        .toLowerCase()
                + "/add-"
                + entityType.getSimpleName()
                        .replaceAll("([a-z])([A-Z]+)", "$1-$2")
                        .toLowerCase()
                + ".vue";
        if (isOverwrite(addFilePath)) {
            logger.info("addView存放路径:{}", addFilePath);
            FreeMarkerUtils
                    .fprint(LOAD_TEMPLATE_CLASS, VUE_ADD, data, addFilePath);
        }
        
        String updateFilePath = BASE_CODE_FOLDER + templateFolderPath
                + "/views/" + packageName + "/"
                + entityType.getSimpleName()
                        .replaceAll("([a-z])([A-Z]+)", "$1_$2")
                        .toLowerCase()
                + "/update-"
                + entityType.getSimpleName()
                        .replaceAll("([a-z])([A-Z]+)", "$1-$2")
                        .toLowerCase()
                + ".vue";
        if (isOverwrite(updateFilePath)) {
            logger.info("updateView存放路径:{}", updateFilePath);
            FreeMarkerUtils.fprint(LOAD_TEMPLATE_CLASS,
                    VUE_UPDATE,
                    data,
                    updateFilePath);
        }
        switch (viewType) {
            case PAGESLIST: {
                String queryPagedListFilePath = BASE_CODE_FOLDER
                        + templateFolderPath + "/views/" + packageName + "/"
                        + entityType.getSimpleName()
                                .replaceAll("([a-z])([A-Z]+)", "$1_$2")
                                .toLowerCase()
                        + "/"
                        + entityType.getSimpleName()
                                .replaceAll("([a-z])([A-Z]+)", "$1-$2")
                                .toLowerCase()
                        + "-pageslist.vue";
                if (isOverwrite(queryPagedListFilePath)) {
                    logger.info("queryPagedListView存放路径:{}",
                            queryPagedListFilePath);
                    FreeMarkerUtils.fprint(LOAD_TEMPLATE_CLASS,
                            VUE_PAGESLIST,
                            data,
                            queryPagedListFilePath);
                }
            }
                break;
            case TREELIST: {
                String queryTreeListFilePath = BASE_CODE_FOLDER
                        + templateFolderPath + "/views/" + packageName + "/"
                        + entityType.getSimpleName()
                                .replaceAll("([a-z])([A-Z]+)", "$1_$2")
                                .toLowerCase()
                        + "/"
                        + entityType.getSimpleName()
                                .replaceAll("([a-z])([A-Z]+)", "$1-$2")
                                .toLowerCase()
                        + "-treelist.vue";
                if (isOverwrite(queryTreeListFilePath)) {
                    logger.info("queryTreeListView存放路径:{}",
                            queryTreeListFilePath);
                    FreeMarkerUtils.fprint(LOAD_TEMPLATE_CLASS,
                            VUE_TREELIST,
                            data,
                            queryTreeListFilePath);
                }
            }
                break;
            case LIST:
            default: {
                String queryListFilePath = BASE_CODE_FOLDER + templateFolderPath
                        + "/views/" + packageName + "/"
                        + entityType.getSimpleName()
                                .replaceAll("([a-z])([A-Z]+)", "$1_$2")
                                .toLowerCase()
                        + "/"
                        + entityType.getSimpleName()
                                .replaceAll("([a-z])([A-Z]+)", "$1-$2")
                                .toLowerCase()
                        + "-list.vue";
                if (isOverwrite(queryListFilePath)) {
                    logger.info("queryListView存放路径:{}", queryListFilePath);
                    FreeMarkerUtils.fprint(LOAD_TEMPLATE_CLASS,
                            VUE_LIST,
                            data,
                            queryListFilePath);
                }
            }
                break;
        }
    }
    
    /**
     * 生成视图逻辑<br/>
     * <功能详细描述>
     * @param entityType [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     */
    public static <T> void generateHtml(Class<?> entityType) {
        generateHtml(entityType,
                ViewTypeEnum.LIST,
                "/src/main/resources/templates/");
    }
    
    /**
     * 生成视图逻辑<br/>
     * <功能详细描述>
     * @param <T>
     * @param entityType
     * @param viewType [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     */
    public static <T> void generateHtml(Class<?> entityType,
            ViewTypeEnum viewType) {
        generateHtml(entityType, viewType, "/src/main/resources/templates/");
    }
    
    /**
     * 生成视图逻辑<br/>
     * <功能详细描述>
     * @param entityType
     * @param viewType [参数说明]
     * @param templateFolderPath 
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     */
    public static <T> void generateHtml(Class<?> entityType,
            ViewTypeEnum viewType, String templateFolderPath) {
        viewType = viewType == null ? ViewTypeEnum.LIST : viewType;
        ViewGenModel viewModel = new JPAViewGeneratorModel(entityType,
                HTML_VALIDATE_EXPRESSION_GENERATOR);
        
        Map<String, Object> data = new HashMap<String, Object>();
        String packageName = getPackageName(entityType);
        data.put("view", viewModel);
        data.put("packageName", packageName);
        
        String basePath = ClassUtils.convertClassNameToResourcePath(
                entityType.getName()) + "/../..";
        basePath = org.springframework.util.StringUtils.cleanPath(basePath);
        
        String addFilePath = BASE_CODE_FOLDER + templateFolderPath + packageName
                + "/add" + entityType.getSimpleName() + ".html";
        if (isOverwrite(addFilePath)) {
            logger.info("addView存放路径:{}", addFilePath);
            FreeMarkerUtils
                    .fprint(LOAD_TEMPLATE_CLASS, HTML_ADD, data, addFilePath);
        }
        
        String updateFilePath = BASE_CODE_FOLDER + templateFolderPath
                + packageName + "/update" + entityType.getSimpleName()
                + ".html";
        if (isOverwrite(updateFilePath)) {
            logger.info("updateView存放路径:{}", updateFilePath);
            FreeMarkerUtils.fprint(LOAD_TEMPLATE_CLASS,
                    HTML_UPDATE,
                    data,
                    updateFilePath);
        }
        
        switch (viewType) {
            case PAGESLIST: {
                String queryPagedListFilePath = BASE_CODE_FOLDER
                        + templateFolderPath + packageName + "/query"
                        + entityType.getSimpleName() + "PagedList.html";
                if (isOverwrite(queryPagedListFilePath)) {
                    logger.info("queryPagedListView存放路径:{}",
                            queryPagedListFilePath);
                    FreeMarkerUtils.fprint(LOAD_TEMPLATE_CLASS,
                            HTML_PAGESLIST,
                            data,
                            queryPagedListFilePath);
                }
            }
                break;
            case TREELIST: {
                String queryTreeListFilePath = BASE_CODE_FOLDER
                        + templateFolderPath + packageName + "/query"
                        + entityType.getSimpleName() + "TreeList.html";
                if (isOverwrite(queryTreeListFilePath)) {
                    logger.info("queryTreeListView存放路径:{}",
                            queryTreeListFilePath);
                    FreeMarkerUtils.fprint(LOAD_TEMPLATE_CLASS,
                            HTML_TREELIST,
                            data,
                            queryTreeListFilePath);
                }
            }
                break;
            case LIST:
            default: {
                String queryPagedListFilePath = BASE_CODE_FOLDER
                        + templateFolderPath + packageName + "/query"
                        + entityType.getSimpleName() + "PagedList.html";
                if (isOverwrite(queryPagedListFilePath)) {
                    logger.info("queryPagedListView存放路径:{}",
                            queryPagedListFilePath);
                    FreeMarkerUtils.fprint(LOAD_TEMPLATE_CLASS,
                            HTML_LIST,
                            data,
                            queryPagedListFilePath);
                }
            }
                break;
        }
    }
    
    /**
     * 生成控制层逻辑
     * <功能详细描述>
     * @param jpaMetaClass
     * @param resultFolderPath [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     */
    public static <T> void generateController(Class<?> entityType) {
        ControllerGenModel controllerModel = new JPAControllerGenModelImpl(
                entityType);
        
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("controller", controllerModel);
        data.put("packageName", getPackageName(entityType));
        
        String basePath = ClassUtils.convertClassNameToResourcePath(
                entityType.getName()) + "/../..";
        basePath = org.springframework.util.StringUtils.cleanPath(basePath);
        
        String controllerFilePath = BASE_CODE_FOLDER + "/src/main/java/"
                + basePath + "/controller/" + entityType.getSimpleName()
                + "Controller.java";
        if (isOverwrite(controllerFilePath)) {
            logger.info("controller存放路径:{}", controllerFilePath);
            FreeMarkerUtils.fprint(LOAD_TEMPLATE_CLASS,
                    CONTROLLER,
                    data,
                    controllerFilePath);
        }
    }
    
    /**
     * 生成业务层逻辑
     * <功能详细描述>
     * @param jpaMetaClass
     * @param resultFolderPath [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     */
    public static <T> void generateService(Class<?> entityType) {
        ServiceGenModel serviceModel = new JPAServiceGeneratorModel(entityType);
        
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("service", serviceModel);
        
        String servicePath = ClassUtils.convertClassNameToResourcePath(
                entityType.getName()) + "/../../service";
        servicePath = org.springframework.util.StringUtils
                .cleanPath(servicePath);
        String serviceFilePath = BASE_CODE_FOLDER + "/src/main/java/"
                + servicePath + "/" + entityType.getSimpleName()
                + "Service.java";
        
        if (isOverwrite(serviceFilePath)) {
            logger.info("service存放路径:{}", serviceFilePath);
            FreeMarkerUtils.fprint(LOAD_TEMPLATE_CLASS,
                    SERVICE,
                    data,
                    serviceFilePath);
        }
    }
    
    /**
     * 生成持久层逻辑
     * <功能详细描述>
     * @param jpaMetaClass
     * @param resultFolderPath [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     */
    public static <T> void generateDao(Class<?> entityType) {
        DaoGenModel daoModel = new JPADaoGeneratorModel(entityType);
        
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("dao", daoModel);
        
        String daoPath = ClassUtils.convertClassNameToResourcePath(
                entityType.getName()) + "/../../dao";
        daoPath = org.springframework.util.StringUtils.cleanPath(daoPath);
        
        String daoFilePath = BASE_CODE_FOLDER + "/src/main/java/" + daoPath
                + "/" + entityType.getSimpleName() + "Dao.java";
        String daoImplFilePath = BASE_CODE_FOLDER + "/src/main/java/" + daoPath
                + "/impl/" + entityType.getSimpleName() + "DaoImpl.java";
        
        if (isOverwrite(daoFilePath)) {
            logger.info("dao存放路径:{}", daoFilePath);
            FreeMarkerUtils.fprint(LOAD_TEMPLATE_CLASS, DAO, data, daoFilePath);
        }
        
        if (isOverwrite(daoImplFilePath)) {
            logger.info("daoImpl存放路径:{}", daoImplFilePath);
            FreeMarkerUtils.fprint(LOAD_TEMPLATE_CLASS,
                    DAOIMPL,
                    data,
                    daoImplFilePath);
        }
    }
    
    /**
     * 生成SqlMap
     * <功能详细描述>
     * @param jpaMetaClass
     * @param resultFolderPath [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     */
    public static <T> void generateSqlMap(Class<?> entityType) {
        SqlMapGenModel sqlmap = new JPASqlMapGeneratorModel(entityType);
        
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("sqlmap", sqlmap);
        
        String sqlmapPath = ClassUtils.convertClassNameToResourcePath(
                entityType.getName()) + "/../../dao/impl";
        sqlmapPath = org.springframework.util.StringUtils.cleanPath(sqlmapPath);
        
        String sqlmapFilePath = BASE_CODE_FOLDER + "/src/main/java/"
                + sqlmapPath + "/" + entityType.getSimpleName() + "SqlMap.xml";
        
        if (isOverwrite(sqlmapFilePath)) {
            logger.info("sqlmap存放路径:{}", sqlmapPath);
            FreeMarkerUtils
                    .fprint(LOAD_TEMPLATE_CLASS, SQLMAP, data, sqlmapFilePath);
        }
    }
    
    /**
     * 生成脚本<br/>
     * <功能详细描述>
     * @param entityType [参数说明]
     * 
     * @return void [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     */
    public static <T> void generateDBScript(Class<?> entityType) {
        Map<String, Object> data = new HashMap<String, Object>();
        
        //数据脚本映射
        JPADBScriptGeneratorModel dbScript = new JPADBScriptGeneratorModel(
                entityType, DATASOURCE_TYPE.getDialect4DDL());
        data.put("dbScript", dbScript);
        
        //代码生成路径生成
        String[] arrs = entityType.getName().split("\\.");
        String packageName = arrs[arrs.length - 3];
        String dbScriptPath = BASE_CODE_FOLDER + "/dbscript/"
                + DATASOURCE_TYPE.toString().toLowerCase() + "/01basisScript/"
                + packageName + "/tables/"
                + dbScript.getTableName().toLowerCase() + ".sql";
        
        if (isOverwrite(dbScriptPath)) {
            logger.info("mysql脚本存放路径:{}", dbScriptPath);
            FreeMarkerUtils
                    .fprint(LOAD_TEMPLATE_CLASS, DBSCRIPT, data, dbScriptPath);
        }
    }
    
    /**
     * 获取包名<br/>
     * <功能详细描述>
     * @param entityType
     * @return [参数说明]
     * 
     * @return String [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     */
    private static String getPackageName(Class<?> entityType) {
        String servicePath = ClassUtils.convertClassNameToResourcePath(
                entityType.getName()) + "/../../";
        servicePath = org.springframework.util.StringUtils
                .cleanPath(servicePath);
        String[] servicePaths = StringUtils.split(servicePath, "/");
        String packageName = servicePaths[servicePaths.length - 1];
        return packageName;
    }
    
    /**
     * 确认文件是否存在<br/>
     * <功能详细描述>
     * @param filePath
     * @return [参数说明]
     * 
     * @return boolean [返回类型说明]
     * @exception throws [异常类型] [异常说明]
     * @see [类、类#方法、类#成员]
     */
    public static boolean isOverwrite(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return true;
        }
        if (NEED_CONFIRM_WHEN_EXSITS) {
            int flag = JOptionPane.showConfirmDialog(null,
                    MessageUtils.format("文件:[{}]已存在,是否确认覆盖?", filePath),
                    "提示",
                    JOptionPane.YES_NO_OPTION);
            return flag == 0;
        } else {
            return true;
        }
    }
}
